﻿using Aop.Api.Encryption;
using System;
using System.Collections.Generic;
using System.DAL;
using System.Dto;
using System.IBLL;
using System.IDAL;
using System.Linq;
using System.Models;
using System.Models.Models;
using System.Text;
using System.Threading.Tasks;

namespace System.BLL
{
    public class SystemManager : ISystemManager
    {
        private CryptoHelper helper;

        /// <summary>
        /// 日志信息添加
        /// </summary>
        /// <param name="SettingType">日志类型</param>
        /// <param name="SettingText">日志内容</param>
        /// <param name="SettingName">操作人</param>
        /// <returns></returns>
        public async Task AddLogs(string SettingType, string SettingText, string SettingName)
        {
            using (ISystemSettingService systemSvc = new SystemSettingService())
            {
                await systemSvc.CreateAsync(new SystemSetting() { SettingType = SettingType, SettingText = SettingText, SettingName = SettingName });
            }
        }

        public async Task AddNewDeparTmentRole(string Name, string Remark)
        {
            using (IDepartmentRoleService departmentSvc = new DepartmentRoleService())
            {
                await departmentSvc.CreateAsync(new DepartmentRole() { DepartmentRoleName = Name, Remark = Remark });
            }
        }

        public async Task AddNewMnus(AddMenusDto Menu)
        {
            using (IMenusService systemSvc = new MenusService())
            {
                Menus menu = new Menus()
                {
                    Title = Menu.Title,
                    Pid = Menu.Pid,
                    Icon = Menu.Icon,
                    Href = Menu.Href
                };
                await systemSvc.CreateAsync(menu);
            }
        }

        public async Task AddNewStaff(string StaffName, string PassWord, string Sex, int DepartmentRoleId, string Wages)
        {
            using (IStaffService serviceSvc = new StaffService()) 
            {
                helper = new CryptoHelper();
                Staff staff = new Staff()
                {
                    StaffName = StaffName,
                    PassWord = helper.Encrypt(PassWord),
                    Sex = Sex=="1"? true:false,
                    DepartmentRoleId = DepartmentRoleId,
                    Wages = double.Parse(Wages)
                };
                await serviceSvc.CreateAsync(staff);
            }
        }

        public async Task AssignPermissions(int id, string like, string DepartmentRoleName)
        {
            using (IJurisdictionService jurisdictionSvc = new JurisdictionService()) 
            {
                var likedata = like.Split(',');
                var IdList = jurisdictionSvc.GetAllAsync().Where(m => m.DepartmentRoleId == id).Select(m => m.Id).ToList();
                foreach(var list in IdList)
                {
                    await jurisdictionSvc.RemoveByTrueAsync(list,false);
                }
                foreach(var list in likedata)
                {
                    Jurisdiction jurisdiction = new Jurisdiction()
                    {
                        PowerName = DepartmentRoleName,
                        MenusId = int.Parse(list),
                        DepartmentRoleId = id
                    };
                    await jurisdictionSvc.CreateAsync(jurisdiction,false);
                }
                await jurisdictionSvc.Save();
            }
        }

        public async Task DelDepartmentRoleById(int id)
        {
            using (IDepartmentRoleService departmentSvc = new DepartmentRoleService())
            {
                await departmentSvc.RemoveAsync(id);
            }
        }

        public async Task DelMenusById(int id)
        {
            using (IMenusService menusScv = new MenusService())
            {
                await menusScv.RemoveAsync(id);

            }
        }

        public async Task DelStaffById(int id)
        {
            using(IStaffService staffServiceSvc = new StaffService()) 
            {
                await staffServiceSvc.RemoveAsync(id);
            }
        }

        public async Task EditDepartmentRoleByDto(AllDepartmentRoleListDto dto)
        {
            using (IDepartmentRoleService departmentRoleSvc = new DepartmentRoleService())
            {
                var list = departmentRoleSvc.GetOneByIdAsync(dto.Id);
                list.DepartmentRoleName = dto.DepartmentRoleName;
                list.Remark = dto.Remark;
                await departmentRoleSvc.EditAsync(list);
            }
        }

        public async Task EditOneMenus(AllMenusListDto listDto)
        {
            using (IMenusService systemSvc = new MenusService())
            {
                var menus = systemSvc.GetOneByIdAsync(listDto.Id);
                menus.Title = listDto.Title;
                if(listDto.Pid != ""&&listDto.Pid!=null)
                    menus.Pid = int.Parse(listDto.Pid);
                menus.Icon = listDto.Icon;
                menus.Status = int.Parse(listDto.Status)==0? false:true;
                menus.Remark = listDto.Remark;
                menus.Href = listDto.Href;
                await systemSvc.EditAsync(menus);
            }
        }

        public async Task EditOneStaff(AllStaffListDto listDto)
        {
            using (IStaffService staffService = new StaffService())
            {
                helper = new CryptoHelper();
                var staff = staffService.GetOneByIdAsync(listDto.Id);
                staff.StaffName = listDto.StaffName;
                staff.PassWord = helper.Encrypt(listDto.PassWord);
                staff.Email = listDto.Email;
                staff.Iphone = listDto.Iphone;
                staff.Sex = listDto.Sex == "1" ? true : false;
                staff.DepartmentRoleId = listDto.DepartmentRolel;
                staff.Wages = double.Parse(listDto.Wages);
                staff.Remark = listDto.Remark;
                await staffService.EditAsync(staff);
            }
        }

        public List<AllMenusListDto> GetAllData()
        {
            //IMenusService systemSvc = new MenusService();
            using(IMenusService systemSvc = new MenusService())
            {
                return systemSvc.GetAllAsync().Select(m => new AllMenusListDto()
                {
                    Id = m.Id,
                    Pid = m.Pid == null ? "-1" : m.Pid.ToString(),
                    Title = m.Title,
                    Icon = m.Icon,
                    Href = m.Href == "" ? "--" : m.Href,
                    Target = m.Target,
                    Sort = m.Sort,
                    Status = m.Status == true ? "在使用" : "已弃用",
                    CreateTime = m.CreateTime.ToString()
                }).ToList();
            }
            

        }

        public List<AllDepartmentRoleListDto> GetAllDepartmentRoleList(int limit, int page, string DepartmentRoleName, out int datalet)
        {
            using (IDepartmentRoleService departmentRoleSvc = new DepartmentRoleService())
            {
                var data = departmentRoleSvc.GetAllAsync().Select(m=> new AllDepartmentRoleListDto()
                {
                    Id = m.Id,
                    DepartmentRoleName = m.DepartmentRoleName,
                    CreateTime = m.CreateTime.ToString(),
                    IsRemoved = m.IsRemoved.ToString(),
                    Remark = m.Remark
                }).ToList();

                foreach(var list in data)
                {
                    list.CreateTime = DateTime.Parse(list.CreateTime).ToString("yyyy-MM-dd HH:mm:ss");
                }

                if (!(DepartmentRoleName == "" || DepartmentRoleName == null)) 
                {
                    data = data.Where(m => m.DepartmentRoleName.Contains(DepartmentRoleName)).ToList();
                }

                datalet = data.Count();
                data = data.OrderBy(m => m.Id).Skip((page - 1) * limit).Take(limit).ToList();
                return data;
            }
        }

        public List<LogListDto> GetAllLogList(int limit, int page, string LogTitle, string StaffName,out int datalet)
        {
            using(ISystemSettingService systemScv = new SystemSettingService())
            {
                var data = systemScv.GetAllAsync().Select(m=> new LogListDto() 
                {
                    Id = m.Id,
                    SettingText = m.SettingText,
                    SettingType = m.SettingType,
                    SettingName = m.SettingName,
                    CreateTime = m.CreateTime.ToString()
                }).ToList();
                if (!(LogTitle == "" || LogTitle == null))
                {
                    data = data.Where(m => m.SettingText.Contains(LogTitle)).ToList();
                }

                if (!(StaffName == "" || StaffName == null))
                {
                    data = data.Where(m => m.SettingText.Contains(StaffName)).ToList();
                }
                datalet = data.Count();
                data = data.OrderBy(m=>m.Id).Skip((page-1) * limit).Take(limit).ToList();
                return data;
            }
        }

        public List<AllMenusListDto> GetAllMenusList(int limit, int page, string title, string pid, out int datalet)
        {
            using (IMenusService systemScv = new MenusService())
            {
                var data = systemScv.GetAllAsync().Select(m => new AllMenusListDto()
                {
                    Id = m.Id,
                    Pid = m.Pid == null ? "-1" : m.Pid.ToString(),
                    Title = m.Title,
                    Icon = m.Icon,
                    Href = m.Href == "" ? "--" : m.Href,
                    Target = m.Target,
                    Sort = m.Sort,
                    Status = m.Status == true ? "在使用" : "已弃用",
                    CreateTime = m.CreateTime.ToString()
                }).ToList();

                foreach(var list in data)
                {
                    list.CreateTime = DateTime.Parse(list.CreateTime).ToString("yyyy-MM-dd HH:mm:ss");
                }
                
                if (!(title == "" || title == null))
                {
                    data = data.Where(m => m.Title.Contains(title)).ToList();
                }

                if (!(pid == "" || pid == null))
                {
                    data = data.Where(m => m.Pid.Contains(pid)).ToList();
                }
                datalet = data.Count();
                data = data.OrderBy(m => m.Id).Skip((page - 1) * limit).Take(limit).ToList();
                return data;
            }
        }

        public List<StaffListDto> GetAllStaffList(int limit, int page, string StaffName, string Sex, string DepartmentRoleId, out int datalet)
        {
            using (IStaffService staffServiceSvc = new StaffService())
            {

                var data = staffServiceSvc.GetAllAsync().Select(m => new StaffListDto()
                {
                    Id = m.Id,
                    StaffName = m.StaffName,
                    PassWord = m.PassWord,
                    Email = m.Email,
                    Iphone = m.Iphone,
                    Sex = m.Sex.ToString(),
                    DepartmentRoleld = m.DepartmentRoleId.ToString(),
                    Wages = m.Wages.ToString(),
                    CreateTime = m.CreateTime.ToString()
                }).ToList();

                if (!(StaffName == "" || StaffName == null))
                {
                    data = data.Where(m => m.StaffName.Contains(StaffName)).ToList();
                }
                if (!(Sex == "" || Sex == null))//男是1 ，女是0
                {
                    if(Sex=="男")
                        data = data.Where(m => m.Sex == "True").ToList();
                    else
                        data = data.Where(m => m.Sex == "False").ToList();
                }
                if (!(DepartmentRoleId == "" || DepartmentRoleId == null))
                {
                    data = data.Where(m => m.DepartmentRoleld== DepartmentRoleId).ToList();
                }

                datalet = data.Count();

                data = data.OrderBy(m => m.Id).Skip((page - 1) * limit).Take(limit).ToList();
                return data;
            }
        }

        public int GetDepartmentRoleIdByName(string Name)
        {
            using (IDepartmentRoleService departmentSvc = new DepartmentRoleService())
            {
                var list = departmentSvc.GetAllAsync().ToList();
                var id = (from s in list where s.DepartmentRoleName.Trim() == Name select s.Id).ToList()[0];
                return id;
            }
        }

        public List<Menuslists> GetMenuslists(int Id)
        {

            using (IJurisdictionService jurisSvc = new JurisdictionService())
            {           
                var JurisdictionLists = jurisSvc.GetAllAsync().ToList();
                var MenusIdLists = (from i in JurisdictionLists where i.DepartmentRoleId == Id select i.MenusId).ToList();
                List<Menuslists> menuslists = new List<Menuslists>();
                List<Menus> MenusListDatas = new List<Menus>();
                foreach (var MenusId in MenusIdLists)
                {
                    using (IMenusService systemSvc = new MenusService())
                    {
                        var MenusListData = systemSvc.GetOneByIdAsync(MenusId);
                        if (MenusListData.Status)
                        {
                            MenusListDatas.Add(MenusListData);
                        }
                        /*MenusListDatas.Add(MenusListData);
                        var data = buildMenuChild(MenusListDatas);
                        menuslists = data;*/
                    }
                }
                var data = buildMenuChild(MenusListDatas);
                menuslists = data;
                return menuslists;
            }
        }

        public List<GetMenusListToTableSelect> GetMenusListToSelects(int limit, int page, string MenusName, out int datalet)
        {
            var data = GetAllData().ToList().Select(m=>new GetMenusListToTableSelect() 
            {
                Id = m.Id,
                MenusName = m.Title,
                /*Pid = m.Pid == null ? "根菜单" : m.Pid.ToString()*/
                Pid = m.Pid == null ||m.Pid=="-1"? "根菜单" : GetOneMenusById(int.Parse(m.Pid)).Title
            }).ToList();
            if (!(MenusName == "" || MenusName == null))
                data = data.Where(m => m.MenusName.Contains(MenusName)).ToList();
            datalet = data.Count();

            data = data.OrderBy(m => m.Id).Skip((page - 1) * limit).Take(limit).ToList();
            return data;
        }

        public AllDepartmentRoleListDto GetOneDepartmentRoleById(int id)
        {
            using (IDepartmentRoleService departmentRoleSvc = new DepartmentRoleService())
            {
                var data = departmentRoleSvc.GetAllAsync().Where(m=>m.Id==id).Select(m => new AllDepartmentRoleListDto()
                {
                    Id = m.Id,
                    DepartmentRoleName = m.DepartmentRoleName,
                    Remark = m.Remark
                }).FirstOrDefault();
                return data;
            }
        }

        public AllMenusListDto GetOneMenusById(int Id)
        {
            using(IMenusService menusSvc = new MenusService())
            {
                var data = menusSvc.GetOneByIdAsync(Id);
                AllMenusListDto listDto = new AllMenusListDto()
                {
                    Id = data.Id,
                    Pid = data.Pid.ToString(),
                    Title = data.Title,
                    Icon = data.Icon,
                    Href = data.Href,
                    Target = data.Target,
                    Sort = data.Sort,
                    Status = data.Status.ToString(),
                    CreateTime = data.CreateTime.ToString()
                };
                return listDto;
            }
        }

        public AllStaffListDto GetOneStaffById(int Id)
        {
            using(IStaffService staffSvc = new StaffService())
            {
                helper = new CryptoHelper();
                var data = staffSvc.GetOneByIdAsync(Id);
                AllStaffListDto listDto = new AllStaffListDto()
                {
                    Id = data.Id,
                    StaffName = data.StaffName,
                    PassWord = helper.Decrypt(data.PassWord),
                    Email = data.Email,
                    Iphone = data.Iphone,
                    Sex = data.Sex.ToString(),
                    DepartmentRolel = data.DepartmentRoleId,
                    Wages = data.Wages.ToString(),
                    Remark = data.Remark
                };
                return listDto;
            }
        }

        public List<(int Id, string Title)> GettableSelectList(int limit, int page, string keyword, out int datalet)
        {
            datalet = GetAllData().ToList().Count();
            var data = GetAllData().Select(m => (m.Id, m.Title)).Skip((page - 1) * limit).Take(limit).ToList();
            if (!(keyword == "" || keyword == null))
                data = (from i in data where i.Title.Contains(keyword) select (i.Id, i.Title)).ToList();
            return data;
        }

        public List<(int Id, string DepartmentRoleName)> GettableSelectStaffList(int limit, int page, string DepartmentRoleName, out int datalet)
        {
            using (IDepartmentRoleService serviceSvc = new DepartmentRoleService())
            {
                datalet = serviceSvc.GetAllAsync().ToList().Count;
                var data = serviceSvc.GetAllAsync().ToList().Select(m => (m.Id,m.DepartmentRoleName)).Skip((page - 1) * limit).Take(limit).ToList();
                if (!(DepartmentRoleName == "" || DepartmentRoleName == null))
                    data = (from i in data where i.DepartmentRoleName.Contains(DepartmentRoleName) select (i.Id, i.DepartmentRoleName)).ToList();
                return data;
            }
        }

        public List<MenusToDepartmentRoleDto> GitDepartmentRoleToMenus(int id)
        {
            using (IJurisdictionService jurisdictionSvc = new JurisdictionService())
            {
                var menusId = jurisdictionSvc.GetAllAsync().Where(m => m.DepartmentRoleId == id).Select(m => m.MenusId).ToList();
                using(IMenusService menusSvc = new MenusService())
                {
                    var data = menusSvc.GetAllAsync().Select(m => new MenusToDepartmentRoleDto()
                    {
                        id = m.Id,
                        pid = m.Pid,
                        title = m.Title,
                        @checked = menusId.Contains(m.Id) ? true : false
                    }).ToList();
                    List<MenusToDepartmentRoleDto> list = new List<MenusToDepartmentRoleDto>();
                    for(int i = 0; i < data.Count(); i++)
                    {
                        if (data[i].pid == null)
                        {
                            list.Add(data[i]);
                            //data.Remove(data[i]);
                        }
                    }
                    for(int i = 0; i < list.Count(); i++)
                    {
                        for(int j = 0; j < data.Count(); j++)
                        {
                            if (data[j].pid == list[i].id)
                            {
                                list[i].children.Add(data[j]);
                                //data.Remove(data[j]);
                            }
                        }
                    }

                    return list;
                }
            }
        }

        private List<Menuslists> buildMenuChild(List<Menus> menus)
        {
            using (IMenusService systemSvc = new MenusService())
            {
                List<Menuslists> treeList = new List<Menuslists>();

                foreach (var list in menus)
                {
                    if (list.Pid == null)
                    {
                        Menuslists nodetmp = new Menuslists()
                        {
                            title = list.Title,
                            icon = list.Icon,
                            href = list.Href,
                            target = list.Target
                        };
                        nodetmp.child = menus.Where(m => m.Pid == list.Id).Select(m => new Menuslists()
                        {
                            title = m.Title,
                            icon = m.Icon,
                            href = m.Href,
                            target = m.Target
                        }).ToList();
                        treeList.Add(nodetmp);

                    }
                }
                return treeList;
            }
        }
    }
}
